package com.ruoyi.supermarket.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.supermarket.domain.Product;
import com.ruoyi.supermarket.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.supermarket.mapper.CategoryMapper;
import com.ruoyi.supermarket.domain.Category;
import com.ruoyi.supermarket.service.ICategoryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品分类Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-19
 */
@Service
public class CategoryServiceImpl implements ICategoryService 
{
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 查询商品分类
     * 
     * @param categoryId 商品分类主键
     * @return 商品分类
     */
    @Override
    public Category selectCategoryByCategoryId(Long categoryId)
    {
        return categoryMapper.selectCategoryByCategoryId(categoryId);
    }

    /**
     * 查询商品分类列表
     * 
     * @param category 商品分类
     * @return 商品分类
     */
    @Override
    public List<Category> selectCategoryList(Category category)
    {
        return categoryMapper.selectCategoryList(category);
    }

    /**
     * 新增商品分类
     * 
     * @param category 商品分类
     * @return 结果
     */
    @Override
    public AjaxResult insertCategory(Category category)
    {
        //一级分类
        Category info = categoryMapper.selectCategoryByCategoryId(category.getFcategoryId());
        if(info == null){
            category.setFcategoryId(0L);
            category.setAncestors("0");
            category.setCreateTime(LocalDateTime.now());
            category.setCreateName(SecurityUtils.getLoginUser().getUsername());
            Category c = categoryMapper.checkDeptNameUnique(category);
            if(c != null){
                return AjaxResult.error("新增父分类'" + category.getCategoryName() + "'失败，分类名称已存在");
            }
            categoryMapper.insertCategory(category);
            return AjaxResult.success();
        }else{
            Category c = categoryMapper.checkDeptNameUnique(category);
            if(c != null){
                return AjaxResult.error("新增分类'" + category.getCategoryName() + "'失败，分类名称已存在");
            }
            category.setCreateTime(LocalDateTime.now());
            category.setCreateName(SecurityUtils.getLoginUser().getUsername());
            category.setAncestors(info.getAncestors() + "," + category.getFcategoryId());
            categoryMapper.insertCategory(category);
            return AjaxResult.success();
        }

    }

    /**
     * 修改商品分类
     * 
     * @param category 商品分类
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult updateCategory(Category category)
    {
        Product product = new Product();
        product.setCategoryId(category.getCategoryId());
        List<Product> list = productMapper.selectProductList(product);
        if(list!=null && list.size() > 0){
            return AjaxResult.error("该分类下存在商品，禁止修改");
        }
        //检查新修改的是否重名
        Category info = categoryMapper.checkDeptNameUnique(category);
        Long categoryId = category.getCategoryId();
        if(info!=null && info.getCategoryId().longValue() != categoryId.longValue()){
            return AjaxResult.error("修改分类'" + category.getCategoryName() + "'失败，分类名称已存在");
        }


        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateName(SecurityUtils.getLoginUser().getUsername());
        Category newCategory = categoryMapper.selectCategoryByCategoryId(category.getFcategoryId());
        Category oldCategory = categoryMapper.selectCategoryByCategoryId(category.getCategoryId());
        if (StringUtils.isNotNull(newCategory) && StringUtils.isNotNull(oldCategory))
        {
            String newAncestors = newCategory.getAncestors() + "," + newCategory.getCategoryId();
            String oldAncestors = oldCategory.getAncestors();
            category.setAncestors(newAncestors);

            List<Category> children = categoryMapper.selectChildrenCategory(category.getCategoryId());
            for (Category child : children)
            {
                child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            }
            if (children.size() > 0)
            {
                categoryMapper.updateCategoryChildren(children);
            }
        }
        categoryMapper.updateCategory(category);
        return AjaxResult.success();
    }

    /**
     * 批量删除商品分类
     * 
     * @param categoryIds 需要删除的商品分类主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteCategoryByCategoryIds(Long[] categoryIds)
    {
        return null;
    }

    /**
     * 删除商品分类信息
     * 
     * @param categoryId 商品分类主键
     * @return 结果
     */
    @Override
    public AjaxResult deleteCategoryByCategoryId(Long categoryId)
    {
        Product product = new Product();
        product.setCategoryId(categoryId);
        List<Product> list = productMapper.selectProductList(product);
        if(list!=null && list.size() > 0){
            return AjaxResult.error("该分类下存在商品，禁止删除");
        }
        int result = categoryMapper.hasChildByCateforyId(categoryId);
        if(result>0){
            return AjaxResult.error("存在下级分类，禁止删除");
        }
        categoryMapper.deleteCategoryByCategoryId(categoryId);
        return AjaxResult.success();
    }

    @Override
    public boolean checkDeptNameUnique(Category category) {
      Long categoryId = StringUtils.isNull(category.getCategoryId()) ? -1L : category.getCategoryId();
        Category info = categoryMapper.checkDeptNameUnique(category);
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
